unit DataExport;

interface
uses
  DB, Classes, SysUtils, Dialogs, Clipbrd;


procedure ExportDataSetSeparated(Ds: TDataSet; Stream: TStream;
  Separator: Char);
procedure CopyDatasetToClipboard(Ds: TDataSet);

implementation

procedure WriteS(S: String; Stream: TStream);
begin
    Stream.WriteBuffer(S[1], Length(S));
end;

procedure WritelnS(S: String; Stream: TStream);
begin
    S := S + #13#10;
    WriteS(S, Stream);
end;

procedure WriteDelimitedString(Stream: TStream; S: String;
  Separator:Char);
const
  Delimiter = '"';
var
	Value : String;
begin
    Value := StringReplace(S, Delimiter, Delimiter + Delimiter, [rfReplaceAll]);
    if Pos (Separator, Value) > 0 then
    begin
		Value := Delimiter + Value + Delimiter;
    end;

    WriteS (Value, Stream);
end;



procedure ExportDataSetSeparated(Ds: TDataSet; Stream: TStream;
  Separator:Char);
var
  Bookmark : TBookmark;
	i : Integer;
  Colcount : Integer;
begin
  Bookmark := Ds.GetBookmark;
  Ds.DisableControls;
  Ds.First;

  // titles
  Colcount := 0;
	for i := 0 to Ds.FieldCount-1 do
  begin
      if Ds.Fields[i].Visible then
      begin
      	if Colcount > 0 then
          begin
              WriteS (Separator, Stream);
          end;
          WriteDelimitedString(Stream, Ds.Fields[i].DisplayName, Separator);
          Inc (Colcount);
      end;
  end;
  WritelnS ('', Stream); // reavahetus

  // rows
  while not Ds.Eof do
  begin
    Colcount := 0;

	  for i := 0 to Ds.FieldCount-1 do
    begin
      if Ds.Fields[i].Visible then
      begin
    	  if Colcount > 0 then
        begin
          WriteS (Separator, Stream);
        end;
        WriteDelimitedString(Stream, Ds.Fields[i].AsString, Separator);
        Inc (Colcount);
      end;
    end;
    WritelnS ('', Stream); // reavahetus
    Ds.Next;
  end;

  Ds.GotoBookmark(Bookmark);
  Ds.FreeBookmark(Bookmark);
  Ds.EnableControls;
end;

procedure CopyDatasetToClipboard(Ds: TDataSet);
var
	StringStream : TStringStream;
begin
 	StringStream := TStringStream.Create('');
 	ExportDataSetSeparated(Ds, StringStream, #9);
  Clipboard.AsText := StringStream.DataString;
  StringStream.Free;
end;


end.
